import hashlib
import logging
import asyncio
import time
from config.config_util import config
from domain import User

__author__ = 'thanatos'

__COOKIE_KEY = config.session.secret

def user2cookie(user, max_age):
    """
    Generate cookie str by user.
    """
    # build cookie string by: id-expires-sha1
    expires = str(int(time.time() + max_age))
    s = '%s-%s-%s-%s' % (user.id, user.password, expires, __COOKIE_KEY)
    user_auth_cookie = [str(user.id), expires, hashlib.md5(s.encode('utf-8')).hexdigest()]
    return '-'.join(user_auth_cookie)

@asyncio.coroutine
def cookie2user(cookie_str):
    """
    Parse cookie and load user if cookie is valid.
    """
    if not cookie_str:
        return None
    try:
        L = cookie_str.split('-')
        if len(L) != 3:
            return None
        uid, expires, sha1 = L
        if int(expires) < time.time():
            return None
        user = yield from User.find(uid)
        if user is None:
            return None
        s = '%s-%s-%s-%s' % (uid, user.password, expires, __COOKIE_KEY)
        if sha1 != hashlib.md5(s.encode('utf-8')).hexdigest():
            logging.info('invalid sha1')
            return None
        return user
    except Exception as e:
        logging.exception(e)
        return None
